/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Tabs, Table, Popconfirm} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import DescGroup from "../../../components/DescriptionGroup";
import ViewTitle from "../../../components/ViewTitle";
import {ModalFooter, ModalView} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import styles from "../../index.less";
import ModalInboundLotDetail from "../../store/modal/ModalInboundLotDetail";
import {findInboundLots} from "../../../services/store";
import ModalCreateOrEditPaymentRecord from "../../finance/modal/ModalCreateOrEditPaymentRecord";

const {TabPane} = Tabs;
moment.locale('zh-cn');
const table = 'ProcureOrder';
@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material, finance,
            store, procure
          }) => ({...user, ...material, ...dynamicLabel, ...global, ...procure, ...finance, ...store}))
export default class ModalProcureOrderDetail extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {values, dispatch, treeId} = this.props;
    const {code} = values;
    dispatch && dispatch({
      type: 'procure/findOne',
      payload: {code}
    });
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table: 'InboundOrder'}
    });
    dispatch({
      type: 'global/getModel',
      payload: {table: 'Payment'}
    });
    dispatch({
      type: 'procure/findMaterialRecordByOrderCodeMany',
      payload: {procureOrderCode: code}
    });
    dispatch({
      type: 'store/findInboundLots',
      payload: {procureOrderCode: code}
    });
    this.props.dispatch({
      type: 'finance/findRecordMany',
      payload: {orderCode: code, table: 'Payment', treeId: treeId}
    });
  }

  renderFoot = () => {
    const {foot, value, modalRef, callback} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef, values} = this.props;
            const {code} = values;
            this.props.dispatch({
              type: 'procure/review',
              payload: {code, reviewStatus: '同意'}
            }).then(res => {
              callback();
              //  modalRef.close();
            });

          }}>同意</Button>

          <Button type={'danger'} onClick={() => {
            const {modalRef, values} = this.props;
            const {code} = values;
            this.props.dispatch({
              type: 'procure/review',
              payload: {code, reviewStatus: '驳回'}
            }).then(res => {
              callback();
              // modalRef.close();
            });
          }}>驳回</Button>
        </ModalFooter>
      );
    }
  };
  onInboundLotDetail = values => {
    ModalView.open(ModalInboundLotDetail, {
      title: '入库记录详情',
      width: '920px',
      maskClosable: false
    }, {
      values
    });
  };

  cols = () => {
    return [
      {
        title: "物料", dataIndex: 'name', key: 'name', render: (value, record) => {
          const {code} = record;
          return this.getProductionElement(code, value);
        }
      },
      {title: "物料规格", key: "spec", dataIndex: "spec"},
      {title: "物料类型", key: "type", dataIndex: "type"},
      {title: "物料编号", key: "number", dataIndex: "number"},
      {title: "采购数量", key: "count", dataIndex: "count"},
      {
        title: "占用数量", key: "useCount", dataIndex: "useCount", render: value => {
          return <div>{value ? value : 0}</div>;
        }
      },
      {
        title: "可用数量", key: "useCount", dataIndex: "useCount", render: (value, option) => {
          const {count = 0, useCount = 0} = option;
          const color = useCount > count || useCount === count ? "#f22" : "#22f";
          return <div style={{color}}>{count - useCount}</div>;
        }
      },
      {title: "税率", key: "taxRate", dataIndex: "taxRate"},
      {title: "单价", key: "price", dataIndex: "price"},
      {title: "运费", key: "shippingFee", dataIndex: "shippingFee"},
      {title: "去向", key: "target", dataIndex: "target"}
    ];
  };
  onCreateOrEdit = record => {
    const title = record ? '编辑记录' : "创建记录";
    const type = record ? "finance/updateRecord" : "finance/createRecord";
    const {customers, vendors, treeId, procureOrder} = this.props;
    ModalView.open(ModalCreateOrEditPaymentRecord,
      {
        title,
        width: '1080px'
      }, {
        values: record, table, customers, vendors, order: procureOrder,
        callback: (payload) => {
          payload.table = "Payment";
          payload.divison = procureOrder.divison;
          payload.code = record ? record.code : 'FIN' + new Date().valueOf();
          payload.treeId = treeId;
          payload.treeName = this.props.title;

          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  payCols() {
    const {isFinance} = this.props;
    return [
      {title: "户名", dataIndex: '_accountName', key: '_accountName'},
      {title: "开户行", dataIndex: 'openingBank', key: 'openingBank'},
      {title: "支出付款方式", dataIndex: 'payWay', key: 'payWay'},
      {title: "付款金额", dataIndex: 'paymentAmount', key: 'paymentAmount'},
      {
        title: "付款日期", dataIndex: 'date', key: 'date', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {
        title: "操作", dataIndex: 'opt', key: 'opt', render: (value, record) => {
          const {code} = record;
          return <span>
                      {
                        <a style={{marginRight: '6px'}}
                           onClick={() => {
                             this.onCreateOrEdit(record);
                           }}
                           disabled={!isFinance}
                        >编辑</a>
                      }
            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                this.props.dispatch({
                  type: "finance/deleteRecord",
                  payload: {table: 'Payment', code}
                }).then(res => {
                  this.requestReturn(res);
                  this.componentDidMount();
                });
              }}
              okText="是"
              cancelText="否"
            >
              <a disabled={!isFinance}>删除</a>
            </Popconfirm>}
           </span>;
        }
      }

    ];
  }

  render() {
    const {
      style,
      procureOrder = {},
      inboundLots = [],
      materialRecords = [],
      isReview, isAcceptance = false,
      cols = 4
    } = this.props;

    const model = this.props[`${table}Model`];
    const okStr = isAcceptance ? "验收通过" : "同意";
    const {fileList, reviewStatus, acceptanceStatus,code} = procureOrder;

    if (!model) return;
    const _values = _.cloneDeep(procureOrder);
    const _labels = _.filter(model, (item, key) => {
      if (key !== 'labels' && _.includes(item.enableArea, 'detail')) {
        item.key = key;
        return item;
      }
    });
    _.map(_labels, item => {
      const {_type, key} = item;
      if (_type.toLowerCase() === 'switch') {
        _values[key] = _values[key] ? "是" : "否";
      }
      if (_type.toLowerCase() === 'date') {
        _values[key] = _values[key] ? moment(_values[key]).format('YYYY-MM-DD') : '';
      }
    });

    const lotCols = this.getInboundLotCols();
    // console.log('valuess', values);
    lotCols.push({
      title: '操作', dataIndex: 'operation', key: 'operation',
      width: 120, fixed: 'right',
      render: (value, record) => {
        return (
          <span>
           {<a style={{marginRight: '6px'}}
               onClick={() => this.onInboundLotDetail(record)}>详情</a>}
            </span>
        );
      }
    });
    return (
      <div style={{...style}}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="采购" key="1">
            <ViewTitle
              title={'采购单信息'}
              level={1}
              actions={[
                // !isReview && <Button type={'danger'} onClick={() => {
                //   onClose();
                // }}>退出</Button>,

                (isReview || isAcceptance) &&
                <Button disabled={reviewStatus === okStr || acceptanceStatus === okStr} type="primary" onClick={() => {

                  // if (isReview && reviewStatus === '同意') return;
                  // if (isAcceptance && acceptanceStatus === '验收通过') return;
                  console.log('xxxxx isAcceptance',isReview,isAcceptance)
                  isReview && this.props.dispatch({
                    type: 'procure/review',
                    payload: {code, reviewStatus: '同意'}
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                  isAcceptance && this.props.dispatch({
                    type: 'procure/review',
                    payload: {code, acceptanceStatus: '验收通过'}
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });

                }}>{okStr}</Button>,

                (isReview || isAcceptance) &&
                <Button type={'danger'} disabled={reviewStatus === '驳回'} onClick={() => {

                  // if (isReview && reviewStatus === '驳回') return;
                  // if (isAcceptance && acceptanceStatus === '驳回') return;

                  isReview && this.props.dispatch({
                    type: 'procure/review',
                    payload: {code, reviewStatus: '驳回'}
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });

                  isAcceptance && this.props.dispatch({
                    type: 'procure/review',
                    payload: {code, acceptanceStatus: '驳回'}
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });

                }}>驳回</Button>
              ]}
            ></ViewTitle>
            <DescGroup
              {...{
                labels: _labels,
                values: _values,
                size: 'default',
                column: cols
              }}
            ></DescGroup>
            <ViewTitle
              title={'物料列表'}
              level={1}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.cols()}
              dataSource={materialRecords}
              scroll={{x: true}}
              pagination={{pageSize: 100}}
              //scroll={{ x: 1300 }}
            ></Table>
            {this.getPicCard(fileList)}
          </TabPane>
          <TabPane tab="入库" key="2">
            {<ViewTitle
              title={'入库批次列表'}
              level={1}
            ></ViewTitle>}
            <Table
              className={styles.antTable}
              bordered={true}
              columns={lotCols}
              dataSource={inboundLots}
              scroll={{x: true}}
              pagination={true}
              //scroll={{ x: 1300 }}
            ></Table>
          </TabPane>
          {/*<TabPane tab="付款" key="3">*/}
          {/*  {<ViewTitle*/}
          {/*    title={'付款记录列表'}*/}
          {/*    level={1}*/}
          {/*    actions={isFinance && <Button type="primary" onClick={() => {*/}
          {/*      this.onCreateOrEdit();*/}
          {/*    }}>添加</Button>}*/}
          {/*  ></ViewTitle>}*/}
          {/*  <Table*/}
          {/*    className={styles.antTable}*/}
          {/*    bordered={true}*/}
          {/*    columns={this.payCols()}*/}
          {/*    dataSource={PaymentRecords}*/}
          {/*    scroll={{x: true}}*/}
          {/*    pagination={true}*/}
          {/*    //scroll={{ x: 1300 }}*/}
          {/*  ></Table>*/}
          {/*</TabPane>*/}

        </Tabs>

        {/*{isReview && this.renderFoot()}*/}
      </div>

    );
  }
}

